package com.ideal.frame.sys.service;

import com.ideal.frame.jpa.JpaRepositoryImpl;
import com.ideal.frame.sys.entity.SysLog;
import com.ideal.frame.util.NetworkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: jin
 * @CreateTime: 2020-01-12 14:31
 * @Description: 系统日志service
 */
@Service
@Transactional
@Slf4j
public class SysLogService {
    @PersistenceContext
    protected EntityManager entityManager;
    private JpaRepositoryImpl<SysLog,Long> logJpaRepo;

    @PostConstruct
    public void initRepo(){
        logJpaRepo=new JpaRepositoryImpl<>(SysLog.class,entityManager);
    }


    public SysLog getLogByRequest(HttpServletRequest request){
        String userAgent = NetworkUtil.getUserAgent(request);
        String ipAddress = NetworkUtil.getIpAddress(request);
        String param = NetworkUtil.getParams(request);
        SysLog sysLog = new SysLog.Builder()
                .remoteAddr(ipAddress).requestUri(request.getRequestURI()).method(request.getMethod())
                .params(param).userAgent(userAgent)
                .build();
        return sysLog;
    }

    @Transactional
    public void save(SysLog sysLog){
        logJpaRepo.save(sysLog);
    }

}
